<template>
  <Layout>


    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据！" :loading="buttonLoading" size="small"
           border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
              @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
      </Col>
    </Row>


  </Layout>
</template>

<script>
import {Api} from '../../../api/index.js'
import {sessionStorage} from '../../../common/cacheUtils.js';
import cascaderDom from '../../../components/cascader-dom.vue';


export default {
  components: {
    cascaderDom
  },
  data() {
    return {
      buttonLoading1: false,
      groupLeaderList: [],
      history: [],
      loading2: false,
      model3: false,
      missionList: [],
      fileUrl: Api.interestedPartiesUserFile,
      currentUser:sessionStorage('userId').getObject('userId'),
      missionSelectModal: false,
      upLoadList1: [],
      appStatusList: [],
      locationList: [],
      stdRankList: [],
      downloadUrl: Api.downloadMongoFile,
      upUrl: Api.uploadMongoFile,
      form1: {},
      uploadList: [],
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      dataTable: [],
      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          title: '被审计单位',
          minWidth: 300,
          align: 'center',
          key: 'auditedOrgName',
        },
        {
          title: '审计完成时间',
          minWidth: 150,
          align: 'center',
          key: 'startDate',
          render: (h, params) => {
            return h('span', this.formatDate(new Date(params.row.auditTime), 'yyyy-MM-dd'));
          }
        },
        {
          title: '问题清单到期时间',
          minWidth: 150,
          align: 'center',
          key: 'endDate',
          render: (h, params) => {
            return h('span', this.formatDate(new Date(params.row.problemTimeOut), 'yyyy-MM-dd'));
          }
        },
      ],
      ruleCustom: {
        missionId: [{
          validator: (rule, value, callback) => {
            if (this.form1datacopy.missionId == undefined || this.form1datacopy.missionId == null || this.form1datacopy.missionId == '') {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        startDate: [{
          validator: (rule, value, callback) => {
            if (this.form1datacopy.startDate == undefined || this.form1datacopy.startDate == null || this.form1datacopy.startDate == '') {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        userPhone: [{
          validator: (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(this.form1datacopy.userPhone))) {
              callback(' ');
              // this.$Message.error("请填写有效的的手机号")
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],
        endDate: [{
          validator: (rule, value, callback) => {
            if (this.form1datacopy.endDate == undefined || this.form1datacopy.endDate == null || this.form1datacopy.endDate == '') {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],

      },
      auditLeaderList: [],
      auditedOrgName: '',
      auditedOrgId: '',
      add: false,
      model1: false,
      model2: false,
      showdata: {},
      location: null,
      form1datacopy: {},
      files: [],
      buttonLoading: false,
      tableHeight: 10,
    }
  },
  mounted() {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    this.query();
  },
  methods: {
    showHistory(row) {
      this.model3 = true;
      this.loading2 = true;
      this.$http.get(Api.getHistory + '/' + row.procinstId, {params: {}}).then((res) => {
        this.history = res.data;
        this.loading2 = false;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    downloadFile(guideId, file) {
      let url = this.fileUrl + '/file/' + file.id;
      this.$http.get(url, {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        console.log(res)
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = file.fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    remove1(id) {
      console.log(id)
      let url = this.fileUrl + '/file/' + id;
      this.$http.delete(url).then((res) => {
        this.getFiles()
      })
    },

    beforeUpload(file) {
      console.log(this.uploadList)
      let formData = new FormData();
      formData.append("files", file); // 文件对象
      let url = this.fileUrl + '/' + this.form1datacopy.id + '/files/adtReport'
      this.$http.post(url, formData).then((res) => {
        if (res.data.result == "success") {
          this.$Message.info("文件上传成功")
          this.getFiles();
        }
      })
      return false
    },
    async getFiles() {
      let url = this.fileUrl + '/' + this.form1datacopy.id + '/files/adtReport'
      await this.$http.get(url).then((res) => {
        if (res.data.result == "success") {
          this.uploadList = res.data.data
          console.log(this.uploadList);
        }
      })
    },
    setOrgId(data) {
      this.form1.orgId = data[data.length - 1];
    },
    downloadTemplate(){
      this.$http.get(Api.downloadadtReport, {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = "安全审计报告模板-2021.docx" //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    setOrgName(data) {
      this.form1.auditOrgName = data;
    },
    reportInfo(row) {
      let user = sessionStorage('userId').getObject('userId');
      let istrue = confirm("是否上报该条记录？");
      if (istrue) {
        this.buttonLoading = true;
        let data = {
          key: "adtReport",
          createUserId: user.userId,
          userName: user.userName,
          workId: row.reportId,
          formKey: "adtReportForApproval",
          user1: row.supervisorId,
          user2: row.groupLeader,
          user3: row.auditLeader,
        };
        this.$http.post(Api.submit, data).then(function (res) {
          this.buttonLoading = false;
          this.$Message.success({
            content: '保存成功',
            duration: 4
          });
          this.query();
        }, function (err) {
          this.buttonLoading = false;
          this.$Message.error({
            content: '保存失败',
            duration: 4
          });
        });
      }

    },
    onCancel() {
      this.model2 = false
    },
    closeModal1() {
      this.expertSelectModal = false;
    },
    selectMission(row) {
      this.missionSelectModal = false;
      this.form1datacopy.missionName = row.missionName;
      this.form1datacopy.missionId = row.missionId;
      this.form1datacopy.auditTypeName = row.auditTypeName;
      this.form1datacopy.groupLeaderName = row.groupLeaderName;
      this.form1datacopy.auditOrgName = row.auditedOrgName;
      this.form1datacopy.supervisor = row.supervisor;
      this.form1datacopy.planStart = this.formatDate(new Date(row.planStart), 'yyyy-MM-dd');
      this.form1datacopy.planEnd = this.formatDate(new Date(row.planEnd), 'yyyy-MM-dd');


    },
    deleteFile(index) {
      this.files.splice(index, 1);
    },
    deleteData(params) {
      let url = Api.deleteAdtRectification;
      this.$http.delete(url +"/"+ params.row.id).then((res) => {
        if (res.data.status === 200) {
          this.$Message.success('成功');
          this.query()
        } else if (res.data.status === 201) {
          this.$Message.error(res.data.msg);

        }
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },

    openSelect() {
      this.missionSelectModal = true
    },
    addInfo() {
      this.form1datacopy = {
        id: this.get_uuid(),
        userName:this.currentUser.userName
      };

      this.uploadList = [];
      this.model1 = true;
      this.add = true;
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    handleCancel() {
      this.form1datacopy = {};
      this.model1 = false;
    },
    selectCodingSort() {

    },
    reset() {
      this.$refs.trainOrg.resetCurrentOrg();
      this.form1 = {};
      this.query();


    },
    setUserId(data) {
      this.form1datacopy.projectManager = data[data.length - 1];
    },
    setUserName(data) {
      this.form1datacopy.projectManagerName = data;
    },

    setUserId1(data) {
      this.form1datacopy.groupLeader = data[data.length - 1];
    },
    setUserName1(data) {
      this.form1datacopy.userName = data;
    },

    query() {
      this.buttonLoading = true
      let orgId = sessionStorage('userId').getObject('userId').companyId;
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        orgId:orgId,
      };
      let url = Api.queryProblemTipList;

      this.$http.get(url, {params: data}).then((res) => {

        this.dataTable = res.data.data.data;
        this.pagedata.total = res.data.data.totalSize;
        this.buttonLoading = false
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    async showData(data, flag) {

      this.auditedOrgId = data.row.auditedOrgId;
      this.auditedOrgName = data.row.auditedOrgName;
      if (flag == 1) {
        //查看页面
        this.form1datacopy = data.row;
        await this.getFiles()
        this.model2 = true;
      } else {

        this.add = false;
        this.form1datacopy = JSON.parse(JSON.stringify(data.row));
        this.form1datacopy.startDate = this.formatDate(new Date(this.form1datacopy.startDate), 'yyyy-MM-dd')
        this.form1datacopy.endDate = this.formatDate(new Date(this.form1datacopy.endDate), 'yyyy-MM-dd')
        await this.getFiles()
        this.model1 = true;
      }

    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },

    submit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          //this.form1datacopy.planStart = this.formatDate(new Date(this.form1datacopy.planStart), 'yyyy-MM-dd');
          //this.form1datacopy.planEnd = this.formatDate(new Date(this.form1datacopy.planEnd), 'yyyy-MM-dd');
          this.buttonLoading1 = true;
          if (this.add) {
            let userId = sessionStorage('userId').getObject('userId').userId;
            let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
            this.form1datacopy.createUserId = userId;
            this.form1datacopy.createOrgId = orgId;

            this.$http.post(Api.saveAdtRectification, this.form1datacopy).then((res) => {
              this.buttonLoading1 = false;
              if (res.status === 200) {
                this.$Message.success('成功');
                this.model1 = false;
                this.query()

              } else if (res.data.status === 201) {
                this.$Message.error(res.data.msg);
                this.model1 = false;
              }

            }).catch(e => {
              this.buttonLoading1 = false;
              this.model1 = false;
              this.query();
              this.$Message.error("数据获取失败")
            })
          } else {
            let userId = sessionStorage('userId').getObject('userId').userId;
            let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
            this.form1datacopy.updateUserId = userId;
            this.form1datacopy.updateOrgId = orgId;
            this.$http.put(Api.updateAdtRectification, this.form1datacopy).then((res) => {
              this.buttonLoading1 = false;
              if (res.status === 200) {
                this.$Message.success('成功');
                this.model1 = false;
                this.query()

              } else if (res.data.status === 201) {
                this.$Message.error(res.data.msg);
                this.model1 = false;
              }

            }).catch(e => {
              this.buttonLoading1 = false;
              this.model1 = false;
              this.query();
              this.$Message.error("数据获取失败")
            })
          }


        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    get_uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
      s[8] = s[13] = s[18] = s[23] = "-";

      let uuid = s.join("");
      let reg = new RegExp("-", "g");
      let a = uuid.replace(reg, "");
      console.log(a);
      return a;
    },
  },
  watch: {
    "model1": function (qw, er) {
      if (qw && this.model1) {
        setTimeout(() => {
          this.$refs.childUser.setCurrentOrg();
          this.$refs.childUser1.setCurrentOrg();
        }, 100)
      } else {
        this.$refs.childUser.resetCurrentOrg();
        this.$refs.childUser1.resetCurrentOrg();
      }
    },

  },
}
</script>

<style lang='css' scoped>
@import '../../../index.css';
</style>
